<template>
  <el-aside :width="isCollapse ? '64px' : '200px'">
    <el-scrollbar wrap-class="scrollbar-wrapper">
      <template v-if="!permissionStore.hasGenerated">
        <div class="loading-container">
          <!-- <el-icon class="loading-icon"><Loading /></el-icon> -->
          <span class="loading-text">路由加载中...</span>
        </div>
      </template>
      <template v-else>
        <el-menu
          :default-active="activeMenu"
          background-color="#001529"
          text-color="#bfcbd9"
          active-text-color="#409EFF"
          :collapse="isCollapse"
          :collapse-transition="false"
          router
          unique-opened
        >
          <sidebar-item
            v-for="route in processedRoutes"
            :key="route.path"
            :item="route"
            :base-path="route.path"
          />
        </el-menu>
      </template>
    </el-scrollbar>
  </el-aside>
</template>

<script setup>
import { computed } from 'vue'
import { useRoute } from 'vue-router'
import { usePermissionStore } from '@/stores/permission'
import SidebarItem from './SidebarItem.vue'

const route = useRoute()
const permissionStore = usePermissionStore()

// 路由处理逻辑
const processedRoutes = computed(() => {
  const filterRoutes = (routes) => 
    routes
      .filter(route => {
        const hasValidComponent = !!route.component
        const hasVisibleChildren = route.children?.some(child => !child.meta?.hidden)
        return !route.meta?.hidden && (hasValidComponent || hasVisibleChildren)
      })
      .map(route => ({
        ...route,
        path: cleanPath(route.path),
        children: route.children ? filterRoutes(route.children) : []
      }))
  
  return filterRoutes(permissionStore.routes)
})

// 路径格式化方法
const cleanPath = (path) => {
  return path?.replace(/^\/+/, '') || ''
}

// 当前激活菜单
const activeMenu = computed(() => {
  return route.meta.activeMenu || route.path
})

// 接收折叠状态
const props = defineProps({
  isCollapse: {
    type: Boolean,
    default: false
  }
})
</script>

<style lang="scss" scoped>
.el-aside {
  transition: width 0.3s ease;
  background-color: #001529;
  
  .el-menu {
    border-right: none;
    &:not(.el-menu--collapse) {
      width: 200px;
    }
  }
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  
  .loading-icon {
    color: #fff;
    font-size: 24px;
    margin-bottom: 8px;
    animation: rotating 2s linear infinite;
  }
  
  .loading-text {
    color: #fff;
    font-size: 14px;
  }
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>